﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Intelligent.OTC.Domain.Repositories;
using Intelligent.OTC.Common.UnitOfWork;
using Intelligent.OTC.Domain.DataModel;
using System.IO;
using Intelligent.OTC.Common;
using Intelligent.OTC.Common.Utils;
using Intelligent.OTC.Domain;
using System.Web;
using System.Configuration;
using Intelligent.OTC.Common.Exceptions;

namespace Intelligent.OTC.Business
{
    public class CustomerPaymentCircleService
    {
        public OTCRepository CommonRep { get; set; }
        public IBaseDataService BDService { get; set; }
        public const string strPaymentDateCircleKey = "PaymentDateCirclePath";

        public IList<CustomerPaymentCircle> GetCustomerPaymentCircle()
        {
            return CommonRep.GetQueryable<CustomerPaymentCircle>().Where(o => o.Deal == AppContext.Current.User.Deal).ToList();
        }

        public IList<CustomerPaymentCircle> GetCustPaymentCircle(string strCustNum)
        {

            return CommonRep.GetQueryable<CustomerPaymentCircle>().Where(o => o.CustomerNum == strCustNum && o.Deal == AppContext.Current.User.Deal).ToList();

        }

        public IQueryable<CustomerPaymentCircle> GetCircleByCondtion(string custNum,string legal) 
        {
            IQueryable<CustomerPaymentCircle> cusPaymentcircleList;
            if (legal == "null" || string.IsNullOrEmpty(legal) || legal=="undefined")
            {
                 cusPaymentcircleList = CommonRep.GetQueryable<CustomerPaymentCircle>().Where(o => o.CustomerNum == custNum && o.Deal == AppContext.Current.User.Deal);
            }
            else {
                 cusPaymentcircleList = CommonRep.GetQueryable<CustomerPaymentCircle>().Where(o => o.CustomerNum == custNum && o.Deal == AppContext.Current.User.Deal && o.LegalEntity == legal);
            }
            List<CustomerPaymentCircleP> CustomerPaymentcircleList = new List<CustomerPaymentCircleP>();
            CustomerPaymentCircleP cuspaycircle = new CustomerPaymentCircleP();
            int ind = 0;
            foreach (var item in cusPaymentcircleList)
            {
                ind++;
                cuspaycircle = new CustomerPaymentCircleP();
                cuspaycircle.Id = item.Id;
                cuspaycircle.PaymentDay = item.PaymentDay;
              //  cuspaycircle.PaymentWeek = item.PaymentWeek;
                cuspaycircle.weekDay = (item.PaymentDay.DayOfWeek).ToString();
                cuspaycircle.Flg = item.Flg;
                cuspaycircle.Description = item.Description;
                cuspaycircle.CustomerNum = item.CustomerNum;
                cuspaycircle.CreatePersonId = item.CreatePersonId;
                cuspaycircle.CreateDate = item.CreateDate;
                cuspaycircle.LegalEntity = item.LegalEntity;
                cuspaycircle.sortId = ind;
                CustomerPaymentcircleList.Add(cuspaycircle);
            }
            return CustomerPaymentcircleList.AsQueryable<CustomerPaymentCircle>();

         //   return CommonRep.GetQueryable<CustomerPaymentCircle>().Where(o=>o.CustomerNum==custNum && o.Deal==AppContext.Current.User.Deal && o.LegalEntity==legal);
        }

        public string UploadPaymentCircle(string customerNum,string legal)
        {
            //List<Customer> listTable = new List<Customer>();
            CustomerPaymentCircle cusfrFile = new CustomerPaymentCircle();
            //Customer updateCust = new Customer();
            string strline = "";
            string[] aryline;
            StreamReader mysr = null;
            string strCode = "";
            string strpath = "";
            FileUploadHistory fileUpHis = new FileUploadHistory();
            FileService fileService = SpringFactory.GetObjectImpl<FileService>("FileService");

            try
            {
                strCode = Helper.EnumToCode<FileType>(FileType.PaymentDateCircle);
                fileUpHis = fileService.GetSuccessData(strCode);

                //read csv file
                strpath = fileUpHis.ArchiveFileName;
                mysr = new StreamReader(strpath, System.Text.Encoding.Default);
                while ((strline = mysr.ReadLine()) != null)
                {
                    aryline = strline.Split(new char[] { ',' });
                    foreach(string ary in aryline){
                        var paymentcirclelist = GetCustPaymentCircle(customerNum);
                        foreach (var item in paymentcirclelist)
                        {
                            if (Convert.ToDateTime(ary) == item.PaymentDay && item.LegalEntity==legal)
                            {
                                return "PaymentCircle exist repeat!";
                            }
                        }
                        var payday = ary + ' ' + "23:59:59";
                        cusfrFile.PaymentDay = Convert.ToDateTime(payday);
                        var week = Convert.ToInt32(Convert.ToDateTime(ary).DayOfWeek);
                        string weekday = week.ToString();
                        cusfrFile.PaymentWeek = weekday;
                        cusfrFile.CustomerNum = customerNum;
                        cusfrFile.LegalEntity = legal;
                        cusfrFile.CreatePersonId = AppContext.Current.User.EID;
                        cusfrFile.Flg = "0";
                        cusfrFile.CreateDate = AppContext.Current.User.Now;
                        cusfrFile.Deal = AppContext.Current.User.Deal;
                        CommonRep.Add(cusfrFile);
                        //UOW.Commit();
                        //fileUpHis.ProcessFlag = Helper.EnumToCode<UploadStates>(UploadStates.Success);
                        CommonRep.Commit();
                       
                    }
                } 
                       return "Add Success!";
            }
            catch (Exception ex)
            {
                fileUpHis.ProcessFlag = Helper.EnumToCode<UploadStates>(UploadStates.Failed);
                fileService.CommonRep.Commit();
                throw ex;
            }
            finally
            {
                if (mysr != null) { mysr.Close(); }
            }

        }

        public string AddPamentCircle(List<string> pay)
        {
            CustomerPaymentCircle circle = new CustomerPaymentCircle();
            var payday = pay[0] + ' ' + "23:59:59";
            circle.PaymentDay = Convert.ToDateTime(payday);
            var paymentcirclelist = GetCustPaymentCircle(pay[1].ToString());
            foreach (var item in paymentcirclelist)
            {
                if (circle.PaymentDay == item.PaymentDay && item.LegalEntity == pay[2].ToString())
                {
                    return "PaymentCircle exist repeat!";
                }          
            }
            circle.CustomerNum = pay[1].ToString();
            circle.LegalEntity = pay[2].ToString();
            circle.Deal = AppContext.Current.User.Deal;
            var week = Convert.ToInt32(Convert.ToDateTime(pay[0]).DayOfWeek);
            string weekday = week.ToString();
            circle.PaymentWeek = weekday;
            circle.CreatePersonId = AppContext.Current.User.EID;
            circle.Flg = "1";
            circle.CreateDate = AppContext.Current.User.Now;
            if (circle.Id == 0)
            {
               CommonRep.Add(circle);
            }
            //else
            //{
            //    CustomerPaymentCircle old = CommonRep.FindBy<CustomerPaymentCircle>(circle.Id);
            //    ObjectHelper.CopyObjectWithUnNeed(circle, old, new string[] { "Id", "CustomerNum" });
            //}
            CommonRep.Commit();
            return "Add Success!";
        }

        public string AddUploadCircle(string customerNum, string legal)
        {
            FileType fileT = FileType.PaymentDateCircle;
            string archivePath = string.Empty;
            string archiveFileName = string.Empty;
            try
            {
                //upload file to server
                HttpFileCollection files = HttpContext.Current.Request.Files;
                archivePath = ConfigurationManager.AppSettings[strPaymentDateCircleKey].ToString();
                archivePath = archivePath + DateTime.Now.Year.ToString() + "\\" + DateTime.Now.Month.ToString();
                if (Directory.Exists(archivePath) == false)
                {
                    Directory.CreateDirectory(archivePath);
                }

                archiveFileName = archivePath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + fileT.ToString() +
                            "-" + AppContext.Current.User.EID + "-" + DateTime.Now.ToString("HHmmssf") + ".csv";

                FileService service = SpringFactory.GetObjectImpl<FileService>("FileService");
                service.UploadFile(files[0], archiveFileName, fileT);

                return UploadPaymentCircle(customerNum,legal);    
            }
            catch (Exception ex)
            {
                Helper.Log.Error(ex.Message, ex);
                throw new OTCServiceException("Uploaded file failed!");
            }
        }
    }
}
